package com.elephant.core.socket.socket3;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * 3、多个客户端连接同一个服务端
 *
 * 线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。
 * 说明：Executors各个方法的弊端：
 * 1）newFixedThreadPool和newSingleThreadExecutor:
 *   主要问题是堆积的请求处理队列可能会耗费非常大的内存，甚至OOM。
 * 2）newCachedThreadPool和newScheduledThreadPool:
 *   主要问题是线程数最大数是Integer.MAX_VALUE，可能会创建数量非常多的线程，甚至OOM。
 *
 * Positive example 1：
 *     //org.apache.commons.lang3.concurrent.BasicThreadFactory
 *     ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
 *         new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
 *
 *
 *
 * Positive example 2：
 *     ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
 *         .setNameFormat("demo-pool-%d").build();
 *
 *     //Common Thread Pool
 *     ExecutorService pool = new ThreadPoolExecutor(5, 200,
 *          0L, TimeUnit.MILLISECONDS,
 *          new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
 *
 *     pool.execute(()-> System.out.println(Thread.currentThread().getName()));
 *     pool.shutdown();//gracefully shutdown
 * @author hai
 * @description
 * @date 13:42 2018/8/31
 */
public class Server {

    private static final ExecutorService POOL;

    static {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();

        //Common Thread Pool
        POOL = new ThreadPoolExecutor(5, 200,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());


    }

    public static void main(String[] args) throws IOException {

        int port = 8888;
        ServerSocket server = new ServerSocket(port);
        while (true){

            Socket accept = server.accept();
            POOL.submit(new Task(accept));

        }
    }


    static class Task implements Runnable{
        private Socket socket;

        public Socket getSocket() {
            return socket;
        }

        public Task(Socket socket) {
            this.socket = socket;
        }


        @Override
        public void run() {
            try {
                handleSocket();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void handleSocket() throws IOException {

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String temp;
            int index;
            while ((temp = reader.readLine()) != null){
                //遇到eof结束接收
                if((index = temp.indexOf("eof")) != -1){
                    sb.append(temp, 0, index);
                    break;
                }
                sb.append(temp);
            }

            System.out.println("From Client:" + sb);

            Writer writer = new OutputStreamWriter(socket.getOutputStream());
            writer.write("Hello Client");
            writer.write("eof\n");
            writer.flush();
            writer.close();
            reader.close();
            socket.close();
        }
    }
}
